//
//  main.cpp
//  mac_network_reachability
//
//  Created by Constantine Mars on 7/3/13.
//  Copyright (c) 2013 Constantine Mars. All rights reserved.
//

#include <iostream>
#include <SystemConfiguration/SCNetworkReachability.h>
#include <CoreFoundation/CoreFoundation.h>
#include <iostream>

static void ConnectivityMonitorCallback(SCNetworkReachabilityRef target,
                                 SCNetworkConnectionFlags flags,
                                 void *info)
{
    /*
     bool isOnline = (flags & kSCNetworkFlagsReachable) && !(flags & kSCNetworkFlagsConnectionRequired);
     ActivatePolicyAndProfile(POLICYID_CURRENT, isOnline ? PROFILEID_ONLINE : PROFILEID_OFFLINE);
     fprintf(stderr, "current mode: %s (%x)\n", isOnline ? "online" : "offline", (int)flags);
     */
//    CheckConnectivityMode();
    using namespace std;
    cout << "Callback called" << endl;
}

#define PRINT_BOOL(x) \
cout << #x << "=" << (x ? "true" : "false") << endl

int main(int argc, const char * argv[])
{
    using namespace std;
    
    /* FIXME: error handling */
    SCNetworkReachabilityRef monitor;
    SCNetworkReachabilityContext ctx = {0};
    SCNetworkConnectionFlags flags;
    
    monitor = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "255.255.255.255");
    SCNetworkReachabilitySetCallback(monitor, ConnectivityMonitorCallback, &ctx);
    if ( !SCNetworkReachabilityGetFlags(monitor, &flags) )
    {
        std::cerr << "SCNetworkReachabilityGetFlags failed" << endl;
    }
    
    bool isReachable = (flags & kSCNetworkFlagsReachable);
    bool needsConnection = (flags & kSCNetworkFlagsConnectionRequired);
    
//    cout << "isReachable=" << (isReachable ? "true" : "false") << endl;
    PRINT_BOOL(isReachable);
    PRINT_BOOL(needsConnection);
    
    cout << ((isReachable && !needsConnection) ? "reachable" : "not reachable") << endl;
    
//    ConnectivityMonitorCallback(monitor, flags, NULL);
//    SCNetworkReachabilityScheduleWithRunLoop(monitor, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);

    return 0;
}

